<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMAPITagController extends DMAbstractController {

	/**
	 * Outputs all tags.
	 */
	public function index() {
		$uri = DMHTTPRequest::getCurrent()->getURI();
		$random = ($uri->getQueryValue("sort") == "random");
		$page = abs((int) substr($uri->getQueryValue("page"), 0, 7));
		$rpp = abs((int) substr($uri->getQueryValue("rpp"), 0, 4));

		$page = ($page < 1) ? 1 : $page;
		$rpp = ($rpp > 100) ? 100 : $rpp;
		$rpp = ($rpp == 1) ? 50 : ($rpp < 10) ? 10 : $rpp;
		$term = substr($uri->getQueryValue("term"), 0, 100);
		$collections = explode(",", $uri->getQueryValue("collections"));
		$objects = explode(",", $uri->getQueryValue("objects"));

		$ds = DMDataStoreFactory::getDataStore();
		$tq = new DMTagQuery($ds);
		$tq->setPage($page);
		$tq->setNumResultsPerPage($rpp);
		$tq->setSortByFrequency(!$random);
		if ($term) {
			$predicate = new DMQueryPredicate();
			$predicate->setString($term);
			$tq->setPredicates(array($predicate));
		}
		foreach ($collections as $alias) {
			if ($alias) {
				$col = DMCollectionFactory::getCollection(
						DMCollection::getSanitizedAlias($alias));
				$tq->addCollection($col);
			}
		}
		foreach ($objects as $aliasptr) {
			$split = explode("/", $aliasptr);
			if (count($split) == 3 && $split[1] && $split[2]) {
				$col = DMCollectionFactory::getCollection(
						DMCollection::getSanitizedAlias($split[1]));
				$obj = DMObjectFactory::getObject($col, (int) $split[2]);
				$tq->addObject($obj);
			}
		}

		$tags = $tq->getSearchResultsAsCounts();
		$total = $tq->getNumResults();

		$response = new DMHTTPResponse();
		$rep = DMHTTPResponseFactory::getRepresentation();
		$trans = DMHTTPResponseFactory::getTransformer();
		$rep->setBody($trans->transformTagCounts($tags, $page, $rpp, $total));
		$response->setRepresentation($rep);
		$response->send();
		die;
	}

	/**
	 * @param int id
	 */
	public function view($id) {
		$response = new DMHTTPResponse();
		$rep = DMHTTPResponseFactory::getRepresentation();
		$trans = DMHTTPResponseFactory::getTransformer();
		$response->setRepresentation($rep);

		try {
			$tag = DMDataStoreFactory::getDataStore()->loadTag($id);
			if (!$tag->isApproved()) {
				throw new DMUnavailableModelException("Invalid tag.");
			}

			$rep->setBody($trans->transformTag($tag));
		} catch (DMUnavailableModelException $e) {
			$response->setStatusCode(404);
			$rep->setBody($trans->transformException($e));
		}

		$response->send();
		die;
	}

}
